﻿using System;
using System.Windows;
using System.IO;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework.Graphics;

namespace ThreeDWorld
{
    public class TextureCubeReader : ContentTypeReader<TextureCube>
    {
        public override TextureCube Read(ContentReader reader)
        {
            TextureCube texture = new TextureCube(reader.Content.Game.GraphicsDevice, reader.ReadInt32(), false, SurfaceFormat.Color);

            for (int i = 0; i != 6; i++)
            {
                ReadFace(reader, texture);
            }
            return texture;
        }

        private void ReadFace(ContentReader reader, TextureCube texture)
        {
            BitmapImage image = new BitmapImage();
            MemoryStream stream = null;

            try
            {
                image.SetSource(stream = new MemoryStream(reader.ReadByteArray(reader.ReadInt32())));
                image.CopyTo(texture, (CubeMapFace)reader.ReadInt32());
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }
    }
}
